﻿using AutoMapper;
using MediatR;
using WMS_Goodsinfo.Api.Write.Application.Command.商品;
using WMS_Goodsinfo.Domain;
using WMS_Goodsinfo.ErrorCode;
using WMS_Goodsinfo.Infastructure;

namespace WMS_Goodsinfo.Api.Write.Application.Handler.商品
{
    public class CreateInoutHandler : IRequestHandler<CreateInoutCommand, ApiResult<int>>
    {
        private readonly IProductRepository<InOut> _inoutRepo;
        private readonly IProductRepository<Product_Table> _productRepo;
        private readonly IMapper _mapper;
        private readonly ILogger<CreateInoutHandler> logger;

        public CreateInoutHandler(IProductRepository<InOut> inoutRepo, IMapper mapper, IProductRepository<Product_Table> productRepo, ILogger<CreateInoutHandler> logger)
        {
            _inoutRepo = inoutRepo;
            _mapper = mapper;
            _productRepo = productRepo;
            this.logger = logger;
        }
        /// <summary>
        /// 新增出入库流水
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public Task<ApiResult<int>> Handle(CreateInoutCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            var model =_mapper.Map<InOut>(request);
            model.CreateTime= DateTime.Now;
            model.Createer = "张三";

            var res=_inoutRepo.Add(model);
            if(res>0)
            {

                result.Code = StatusEnum.OK;
                result.Data = res;
                result.Message = "添加成功";
                logger.LogInformation("添加出入库流出成功");

                var list = _productRepo.GetAll().FirstOrDefault(p => p.Id == request.ProductI_Id);
                if(model.InOutType=="入库")
                {
                    //修改库存入库量,和总金额
                    list.Current_Inventory = list.Current_Inventory + model.InNumber;
                    list.TotalMoeny=list.TotalMoeny+model.InMoney;
                }
                else
                {
                    //修改库存出库量和总金额
                    list.Current_Inventory = list.Current_Inventory - model.OutNumbber;
                    list.TotalMoeny=list.TotalMoeny-model.OutMoney;
                }
                _productRepo.Update(list);
            }
            else
            {
                result.Code = StatusEnum.Fail;
                result.Data = res;
                result.Message = "添加失败";
                logger.LogError("添加出入库流出失败");
            }
            return Task.FromResult(result);
        }
    }
}
